// +build windows

package main

import (
	"bytes"
	"context"
	"fmt"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"syscall"
	"time"
)

//vlcPlay VLC播放
//FIXME: Win10无法运行，应该是Golang自己的问题，从互联网上搜索的结果是 golang1.17 已经修复了这个问题。
//func vlcPlay(ctx context.Context, dIP, dPort, videoFile string) *exec.Cmd {
//	command := fmt.Sprintf("%q %q --no-interact --miface=%q -R --sout=\"#rtp{dst=%s,port=%s,mux=ts,sap :no-sout-all :sout-keep}\"",
//		Conf.VLCBin, videoFile, Conf.SelectNetworkInterfaceName, dIP, dPort,
//	)
//
//	cmd := exec.CommandContext(ctx, "cmd", "/c", command)
//	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
//
//	return cmd
//}

func vlcPlay(ctx context.Context, dIP, dPort, videoFile string) (*exec.Cmd, error) {
	command := fmt.Sprintf("%q %q --no-interact --miface=%q -R --sout=#rtp{dst=%s,port=%s,mux=ts}",
		Conf.VLCBin, videoFile, Conf.SelectNetworkInterfaceName, dIP, dPort,
	)

	utf8Reader := bytes.NewReader([]byte(command))
	gbkReader := transform.NewReader(utf8Reader, simplifiedchinese.GBK.NewEncoder())

	f, err := ioutil.TempFile("./", "temp*.bat")
	if err != nil {
		return nil, err
	}
	defer func() { // 2s 后删除此文件
		go func() {
			time.Sleep(1 * time.Second)
			os.Remove(f.Name())
		}()
	}()

	if _, err := io.Copy(f, gbkReader); err != nil {
		return nil, err
	}
	_ = f.Close()

	cmd := exec.CommandContext(ctx, "cmd", "/c", f.Name())
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}

	return cmd, nil
}
